from flask import Flask, request, jsonify, session, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
import datetime
from werkzeug.security import generate_password_hash, check_password_hash
import os
import json
import pandas as pd
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///music_app.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'music-exam-secret-key-2024'
app.config['DEBUG'] = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['ALLOWED_EXTENSIONS'] = {'xlsx', 'xls', 'csv'}

db = SQLAlchemy(app)

# 创建上传文件夹
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

# 自定义模板过滤器
@app.template_filter('fromjson')
def fromjson_filter(value):
    """将JSON字符串转换为Python对象"""
    if value is None or value == '':
        return []
    try:
        return json.loads(value)
    except (json.JSONDecodeError, TypeError):
        return []

# ▼▼▼ 数据模型定义 ▼▼▼
class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(120), nullable=False)
    role = db.Column(db.String(20), nullable=False, default='student')

    def set_password(self, password):
        self.password = generate_password_hash(password)
    
    def check_password(self, password):
        return check_password_hash(self.password, password)

class Exam(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    teacher_id = db.Column(db.Integer, nullable=False)
    title = db.Column(db.String(200), nullable=False)
    questions = db.Column(db.Text, nullable=False)
    created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    exam_type = db.Column(db.String(50))
    is_active = db.Column(db.Boolean, default=True)

class ExamRecord(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    student_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    exam_id = db.Column(db.Integer, db.ForeignKey('exam.id', ondelete='CASCADE'), nullable=False)
    answers = db.Column(db.Text, nullable=False)
    score = db.Column(db.Float)
    submitted_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
    
    student = db.relationship('User', backref='exam_records')
    exam = db.relationship('Exam', backref='submissions')

# ▼▼▼ 辅助函数 ▼▼▼
def authenticate_user(username, password):
    user = User.query.filter_by(username=username).first()
    if user and user.check_password(password):
        return user
    return None

def get_available_exams():
    return Exam.query.filter_by(is_active=True).all()

def get_teacher_exams(teacher_id):
    return Exam.query.filter_by(teacher_id=teacher_id).all()

def auto_grade_exam(questions, answers):
    total_score = 0
    correct_count = 0
    
    for i, question in enumerate(questions):
        user_answer = answers.get(f'q{i}', '')
        correct_answer = question.get('correct', '')
        
        # 调试信息
        print(f"题目 {i}: 用户答案='{user_answer}', 正确答案='{correct_answer}'")
        print(f"题目选项: {question.get('options', [])}")
        
        # 比较用户答案和正确答案
        if user_answer == correct_answer:
            correct_count += 1
            print(f"题目 {i}: 正确")
        else:
            print(f"题目 {i}: 错误")
    
    if questions:
        total_score = round((correct_count / len(questions)) * 100, 1)
    
    print(f"总分: {total_score}, 正确数: {correct_count}, 总题数: {len(questions)}")
    return total_score, correct_count, len(questions)

def get_student_records(student_id):
    return ExamRecord.query.filter_by(student_id=student_id).all()

def get_all_records():
    return ExamRecord.query.all()

def parse_questions(questions_json):
    """解析题目JSON"""
    if questions_json is None or questions_json == '':
        return []
    try:
        return json.loads(questions_json)
    except (json.JSONDecodeError, TypeError):
        return []

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

def parse_exam_file(file_path):
    """解析考试文件"""
    try:
        if file_path.endswith('.csv'):
            df = pd.read_csv(file_path)
        else:
            df = pd.read_excel(file_path)
        
        questions = []
        for _, row in df.iterrows():
            question = {
                "content": str(row['题目']),
                "options": [
                    str(row['选项A']),
                    str(row['选项B']),
                    str(row['选项C']),
                    str(row['选项D'])
                ],
                "correct": str(row['正确答案']),
                "type": "single"
            }
            questions.append(question)
        
        return questions
    except Exception as e:
        print(f"解析文件错误: {e}")
        return None

# ▼▼▼ 初始化逻辑 ▼▼▼
first_request_done = False

@app.before_request
def initialize_on_first_request():
    global first_request_done
    if not first_request_done:
        print("执行应用初始化...")
        try:
            db.create_all()
            
            # 创建默认管理员/教师账户
            if not User.query.filter_by(username="teacher").first():
                teacher = User(username="teacher", role="teacher")
                teacher.set_password("teacher123")
                db.session.add(teacher)
                print("创建教师账号: teacher / teacher123")
            
            # 创建学生账户
            if not User.query.filter_by(username="student").first():
                student = User(username="student", role="student")
                student.set_password("student123")
                db.session.add(student)
                print("创建学生账号: student / student123")
            
            # 创建示例考试
            if not Exam.query.first():
                sample_exam = Exam(
                    teacher_id=1,
                    title="音乐理论基础期末考试",
                    questions=json.dumps([
                        {
                            "content": "下列哪个音符是C大调的主音？",
                            "options": ["C", "D", "E", "F"],
                            "correct": "A",  # A对应第一个选项C
                            "type": "single"
                        },
                        {
                            "content": "下列哪个音符是G大调的主音？", 
                            "options": ["G", "A", "B", "C"],
                            "correct": "A",  # A对应第一个选项G
                            "type": "single"
                        }
                    ], ensure_ascii=False),
                    exam_type="期末考试"
                )
                db.session.add(sample_exam)
                print("创建示例考试")
            
            db.session.commit()
            first_request_done = True
            print("初始化完成！")
            
        except Exception as e:
            print(f"初始化错误: {e}")
            db.session.rollback()

# ▼▼▼ 路由定义 ▼▼▼
@app.route('/')
def home():
    return redirect('/login')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        user = authenticate_user(username, password)
        
        if user:
            session['logged_in'] = True
            session['user_id'] = user.id
            session['username'] = user.username
            session['role'] = user.role
            return redirect('/dashboard')
        else:
            return render_template('login.html', error="用户名或密码错误")
    
    return render_template('login.html')

@app.route('/dashboard')
def dashboard():
    if not session.get('logged_in'):
        return redirect('/login')
    
    exams = get_available_exams()
    
    # 预处理考试数据
    processed_exams = []
    for exam in exams:
        questions = parse_questions(exam.questions)
        processed_exams.append({
            'id': exam.id,
            'title': exam.title,
            'exam_type': exam.exam_type,
            'created_at': exam.created_at,
            'questions_count': len(questions),
            'is_active': exam.is_active
        })
    
    records = []
    all_records = []
    teacher_exams = []
    
    if session.get('role') == 'student':
        records = get_student_records(session.get('user_id'))
    elif session.get('role') == 'teacher':
        all_records = get_all_records()
        teacher_exams_data = get_teacher_exams(session.get('user_id'))
        
        # 预处理教师创建的考试
        for exam in teacher_exams_data:
            questions = parse_questions(exam.questions)
            teacher_exams.append({
                'id': exam.id,
                'title': exam.title,
                'exam_type': exam.exam_type,
                'created_at': exam.created_at,
                'questions_count': len(questions),
                'is_active': exam.is_active,
                'submissions_count': len(exam.submissions)
            })
    
    return render_template('dashboard.html',
                           username=session.get('username', ''),
                           role=session.get('role', ''),
                           exams=processed_exams,
                           records=records,
                           all_records=all_records,
                           teacher_exams=teacher_exams)

@app.route('/teacher/create_exam', methods=['GET', 'POST'])
def create_exam():
    if not session.get('logged_in') or session.get('role') != 'teacher':
        return redirect('/login')
    
    if request.method == 'POST':
        # 检查是文件上传还是手动创建
        if 'exam_file' in request.files and request.files['exam_file'].filename != '':
            # 文件上传方式
            title = request.form.get('title')
            exam_type = request.form.get('exam_type')
            
            file = request.files['exam_file']
            if file and allowed_file(file.filename):
                filename = secure_filename(file.filename)
                file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                file.save(file_path)
                
                # 解析文件
                questions = parse_exam_file(file_path)
                
                if questions:
                    exam = Exam(
                        teacher_id=session.get('user_id'),
                        title=title,
                        exam_type=exam_type,
                        questions=json.dumps(questions, ensure_ascii=False)
                    )
                    db.session.add(exam)
                    db.session.commit()
                    
                    # 删除临时文件
                    os.remove(file_path)
                    
                    return redirect('/dashboard')
                else:
                    return render_template('create_exam.html', error="文件格式错误，请确保文件包含正确的题目格式")
            else:
                return render_template('create_exam.html', error="不支持的文件格式，请上传Excel或CSV文件")
        else:
            # 手动创建方式
            title = request.form.get('title')
            exam_type = request.form.get('exam_type')
            question_count = int(request.form.get('question_count', 0))
            
            questions = []
            for i in range(question_count):
                content = request.form.get(f'question_{i}')
                option_a = request.form.get(f'option_a_{i}')
                option_b = request.form.get(f'option_b_{i}')
                option_c = request.form.get(f'option_c_{i}')
                option_d = request.form.get(f'option_d_{i}')
                correct = request.form.get(f'correct_{i}')
                
                if content and option_a and option_b and option_c and option_d and correct:
                    questions.append({
                        "content": content,
                        "options": [option_a, option_b, option_c, option_d],
                        "correct": correct,  # 这里保存的是选项字母 A/B/C/D
                        "type": "single"
                    })
            
            if questions:
                exam = Exam(
                    teacher_id=session.get('user_id'),
                    title=title,
                    exam_type=exam_type,
                    questions=json.dumps(questions, ensure_ascii=False)
                )
                db.session.add(exam)
                db.session.commit()
                return redirect('/dashboard')
            else:
                return render_template('create_exam.html', error="请至少添加一个有效的题目")
    
    return render_template('create_exam.html')

@app.route('/teacher/delete_exam/<int:exam_id>', methods=['POST'])
def delete_exam(exam_id):
    if not session.get('logged_in') or session.get('role') != 'teacher':
        return redirect('/login')
    
    exam = Exam.query.get_or_404(exam_id)
    
    # 先删除相关的考试记录
    ExamRecord.query.filter_by(exam_id=exam_id).delete()
    
    # 再删除考试
    db.session.delete(exam)
    db.session.commit()
    
    return redirect('/dashboard')

@app.route('/teacher/toggle_exam/<int:exam_id>')
def toggle_exam(exam_id):
    if not session.get('logged_in') or session.get('role') != 'teacher':
        return redirect('/login')
    
    exam = Exam.query.get_or_404(exam_id)
    exam.is_active = not exam.is_active
    db.session.commit()
    return redirect('/dashboard')

@app.route('/delete_record/<int:record_id>')
def delete_record(record_id):
    if not session.get('logged_in'):
        return redirect('/login')
    
    record = ExamRecord.query.get_or_404(record_id)
    
    # 检查权限：教师可以删除任何记录，学生只能删除自己的记录
    if session.get('role') == 'teacher' or (session.get('role') == 'student' and record.student_id == session.get('user_id')):
        db.session.delete(record)
        db.session.commit()
    
    return redirect('/results')

@app.route('/exam/<int:exam_id>', methods=['GET', 'POST'])
def exam_page(exam_id):
    if not session.get('logged_in'):
        return redirect('/login')
    
    if session.get('role') != 'student':
        return "只有学生可以参加考试！", 403
    
    exam = Exam.query.get_or_404(exam_id)
    
    if request.method == 'POST':
        # 处理考试提交
        answers = {}
        questions = parse_questions(exam.questions)
        
        for i in range(len(questions)):
            answer = request.form.get(f'q{i}')
            # 这里直接保存用户选择的选项内容
            if answer:
                answers[f'q{i}'] = answer
            else:
                answers[f'q{i}'] = '未作答'
        
        print(f"提交的答案: {answers}")
        print(f"题目数据: {questions}")
        
        # 自动评分
        score, correct_count, total_questions = auto_grade_exam(questions, answers)
        
        # 保存考试记录
        record = ExamRecord(
            student_id=session.get('user_id'),
            exam_id=exam_id,
            answers=json.dumps(answers, ensure_ascii=False),
            score=score
        )
        db.session.add(record)
        db.session.commit()
        
        # 获取当前时间并传递给模板
        current_time = datetime.datetime.now()
        
        return render_template('exam_result.html',
                             exam=exam,
                             score=score,
                             correct_count=correct_count,
                             total_questions=total_questions,
                             questions=questions,
                             answers=answers,
                             current_time=current_time)
    
    # GET 请求 - 显示考试页面
    questions = parse_questions(exam.questions)
    print(f"调试: 找到 {len(questions)} 个题目")
    
    return render_template('exam.html', 
                         exam=exam, 
                         questions=questions,
                         exam_time=60)

@app.route('/results')
def view_results():
    if not session.get('logged_in'):
        return redirect('/login')
    
    if session.get('role') == 'student':
        records = get_student_records(session.get('user_id'))
        return render_template('student_results.html', records=records)
    else:
        all_records = get_all_records()
        return render_template('teacher_results.html', records=all_records)

@app.route('/logout')
def logout():
    session.clear()
    return redirect('/login')

# ▼▼▼ 创建模板文件 ▼▼▼
def create_templates():
    templates_dir = 'templates'
    os.makedirs(templates_dir, exist_ok=True)
    
    # 登录页面模板（保持不变）
    login_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录 - 音乐考试系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .login-container {
            background: white;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.1);
            width: 100%;
            max-width: 400px;
            position: relative;
        }
        .logo { text-align: center; margin-bottom: 30px; }
        .logo h1 { color: #333; font-size: 28px; margin-bottom: 10px; }
        .logo p { color: #666; margin-bottom: 5px; }
        .version-info {
            color: #000000;
            font-size: 12px;
            font-weight: bold;
            margin-top: 5px;
        }
        .form-group { margin-bottom: 20px; }
        label { display: block; margin-bottom: 8px; color: #333; font-weight: bold; }
        input { width: 100%; padding: 12px 15px; border: 2px solid #e1e1e1; border-radius: 8px; font-size: 16px; }
        input:focus { outline: none; border-color: #667eea; }
        button { width: 100%; padding: 12px; background: #667eea; color: white; border: none; border-radius: 8px; font-size: 16px; font-weight: bold; cursor: pointer; }
        button:hover { background: #5a6fd8; }
        .error { color: #e74c3c; text-align: center; margin-top: 15px; padding: 10px; background: #ffeaea; border-radius: 5px; }
        .demo-info { text-align: center; margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 8px; font-size: 14px; color: #666; }
        .footer {
            text-align: center;
            margin-top: 20px;
            padding-top: 15px;
            border-top: 1px solid #e1e1e1;
            color: #999;
            font-size: 12px;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <div class="logo">
            <h1>🎵 音乐考试系统</h1>
            <p>请登录您的账户</p>
            <div class="version-info">测试版...，开发者：肖鹏斌</div>
        </div>
        
        <form method="POST">
            <div class="form-group">
                <label>用户名</label>
                <input type="text" name="username" placeholder="请输入用户名" required>
            </div>
            <div class="form-group">
                <label>密码</label>
                <input type="password" name="password" placeholder="请输入密码" required>
            </div>
            <button type="submit">登录</button>
        </form>
        
        {% if error %}
        <div class="error">{{ error }}</div>
        {% endif %}
        
        <div class="demo-info">
            <strong>测试账号：</strong><br>
            👨‍🏫 教师账号：teacher / teacher123<br>
            👨‍🎓 学生账号：student / student123
        </div>

        <div class="footer">
            © 2024 音乐考试系统 - 测试版本
        </div>
    </div>
</body>
</html>'''
    
    with open(os.path.join(templates_dir, 'login.html'), 'w', encoding='utf-8') as f:
        f.write(login_html)
    
    # 仪表板页面模板（保持不变）
    dashboard_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>音乐考试系统 - 仪表板</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container { max-width: 1200px; margin: 0 auto; }
        .header {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .welcome { color: #333; font-size: 28px; font-weight: bold; }
        .username { color: #667eea; }
        .btn {
            display: inline-block;
            padding: 12px 25px;
            background: #ff6b6b;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: bold;
            transition: all 0.3s ease;
            margin-left: 10px;
        }
        .btn:hover { background: #ff5252; transform: translateY(-2px); }
        .section {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        .section-title { font-size: 24px; color: #333; margin-bottom: 25px; padding-bottom: 15px; border-bottom: 2px solid #f0f0f0; }
        .exam-grid { display: grid; gap: 20px; }
        .exam-card {
            background: #f8f9fa;
            padding: 25px;
            border-radius: 12px;
            border-left: 5px solid #667eea;
            transition: all 0.3s ease;
        }
        .exam-card:hover { transform: translateY(-3px); box-shadow: 0 8px 25px rgba(0,0,0,0.1); background: white; }
        .exam-title { font-size: 20px; color: #333; margin-bottom: 10px; font-weight: bold; }
        .exam-meta { color: #666; margin-bottom: 15px; font-size: 14px; }
        .start-btn, .action-btn {
            display: inline-block;
            padding: 10px 20px;
            color: white;
            text-decoration: none;
            border-radius: 6px;
            font-weight: bold;
            transition: all 0.3s ease;
            margin-right: 10px;
            margin-bottom: 5px;
        }
        .start-btn { background: #667eea; }
        .start-btn:hover { background: #5a6fd8; transform: translateY(-2px); }
        .delete-btn { background: #dc3545; }
        .delete-btn:hover { background: #c82333; transform: translateY(-2px); }
        .toggle-btn { background: #28a745; }
        .toggle-btn:hover { background: #218838; transform: translateY(-2px); }
        .create-btn { background: #17a2b8; }
        .create-btn:hover { background: #138496; transform: translateY(-2px); }
        .record-card { 
            background: #f8f9fa; 
            padding: 20px; 
            border-radius: 10px; 
            margin-bottom: 15px; 
            border-left: 4px solid #28a745;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .score { font-size: 24px; font-weight: bold; color: #28a745; }
        .role-badge {
            display: inline-block;
            padding: 4px 12px;
            background: #667eea;
            color: white;
            border-radius: 20px;
            font-size: 12px;
            margin-left: 10px;
        }
        .teacher-badge { background: #dc3545; }
        .student-badge { background: #28a745; }
        .action-buttons { display: flex; gap: 10px; margin-top: 10px; flex-wrap: wrap; }
        .record-info { flex: 1; }
        .no-data { 
            text-align: center; 
            color: #666; 
            padding: 40px;
            font-style: italic;
        }
        .status-badge {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            margin-left: 10px;
        }
        .status-active { background: #28a745; color: white; }
        .status-inactive { background: #6c757d; color: white; }
        .delete-form { display: inline; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div>
                <h1 class="welcome">欢迎, <span class="username">{{ username }}</span>! 
                    <span class="role-badge {% if role == 'teacher' %}teacher-badge{% else %}student-badge{% endif %}">
                        {% if role == 'teacher' %}教师{% else %}学生{% endif %}
                    </span>
                </h1>
                <p style="color: #666; margin-top: 5px;">
                    {% if role == 'teacher' %}
                    👨‍🏫 教师管理面板 - 您可以创建和管理考试
                    {% else %}
                    👨‍🎓 学生考试面板 - 请选择要参加的考试
                    {% endif %}
                </p>
            </div>
            <div>
                <a href="/results" class="btn" style="background: #28a745;">查看成绩</a>
                {% if role == 'teacher' %}
                <a href="/teacher/create_exam" class="btn" style="background: #17a2b8;">创建新考试</a>
                {% endif %}
                <a href="/logout" class="btn">退出登录</a>
            </div>
        </div>
        
        {% if role == 'student' %}
        <!-- 学生视图 -->
        <div class="section">
            <h2 class="section-title">📝 可用考试</h2>
            <div class="exam-grid">
                {% for exam in exams %}
                <div class="exam-card">
                    <div class="exam-title">{{ exam.title }}</div>
                    <div class="exam-meta">
                        🏷️ 类型: {{ exam.exam_type or '常规测试' }} | 
                        📅 创建时间: {{ exam.created_at.strftime('%Y年%m月%d日') }} |
                        📊 题目数量: {{ exam.questions_count }}
                    </div>
                    <a href="/exam/{{ exam.id }}" class="start-btn">开始考试 →</a>
                </div>
                {% else %}
                <div class="no-data">
                    🎵 暂无可用考试，请联系老师添加考试内容
                </div>
                {% endfor %}
            </div>
        </div>
        
        {% if records %}
        <div class="section">
            <h2 class="section-title">📊 我的考试记录</h2>
            {% for record in records %}
            <div class="record-card">
                <div class="record-info">
                    <h3>{{ record.exam.title }}</h3>
                    <p>提交时间: {{ record.submitted_at.strftime('%Y-%m-%d %H:%M') }}</p>
                </div>
                <div class="score">{{ record.score }}分</div>
            </div>
            {% endfor %}
        </div>
        {% endif %}
        
        {% else %}
        <!-- 教师视图 -->
        <div class="section">
            <h2 class="section-title">👨‍🎓 学生考试记录</h2>
            {% if all_records %}
                {% for record in all_records %}
                <div class="record-card">
                    <div class="record-info">
                        <h3>{{ record.student.username }} - {{ record.exam.title }}</h3>
                        <p>提交时间: {{ record.submitted_at.strftime('%Y-%m-%d %H:%M') }}</p>
                    </div>
                    <div class="score">{{ record.score }}分</div>
                </div>
                {% endfor %}
            {% else %}
                <div class="no-data">
                    📊 暂无学生考试记录
                </div>
            {% endif %}
        </div>
        
        <div class="section">
            <h2 class="section-title">📚 我创建的考试</h2>
            <div class="exam-grid">
                {% for exam in teacher_exams %}
                <div class="exam-card">
                    <div class="exam-title">
                        {{ exam.title }}
                        <span class="status-badge {% if exam.is_active %}status-active{% else %}status-inactive{% endif %}">
                            {% if exam.is_active %}启用{% else %}禁用{% endif %}
                        </span>
                    </div>
                    <div class="exam-meta">
                        🏷️ 类型: {{ exam.exam_type or '常规测试' }} | 
                        📅 创建时间: {{ exam.created_at.strftime('%Y年%m月%d日') }} |
                        📊 题目数量: {{ exam.questions_count }} |
                        👥 提交次数: {{ exam.submissions_count }}
                    </div>
                    <div class="action-buttons">
                        <a href="/teacher/toggle_exam/{{ exam.id }}" class="action-btn toggle-btn">
                            {% if exam.is_active %}禁用考试{% else %}启用考试{% endif %}
                        </a>
                        <form class="delete-form" action="/teacher/delete_exam/{{ exam.id }}" method="POST" onsubmit="return confirm('确定要删除这个考试吗？这将删除所有相关记录！')">
                            <button type="submit" class="action-btn delete-btn">删除考试</button>
                        </form>
                    </div>
                </div>
                {% else %}
                <div class="no-data">
                    📝 您还没有创建任何考试，<a href="/teacher/create_exam" style="color: #667eea;">点击这里创建第一个考试</a>
                </div>
                {% endfor %}
            </div>
        </div>
        {% endif %}
    </div>
</body>
</html>'''
    
    with open(os.path.join(templates_dir, 'dashboard.html'), 'w', encoding='utf-8') as f:
        f.write(dashboard_html)

    # 创建考试页面模板（保持不变）
    create_exam_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>创建考试 - 音乐考试系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #f5f7fa;
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f0f0f0;
        }
        .title {
            color: #333;
            font-size: 28px;
            margin-bottom: 10px;
        }
        .form-group {
            margin-bottom: 25px;
        }
        label {
            display: block;
            margin-bottom: 8px;
            color: #333;
            font-weight: bold;
            font-size: 16px;
        }
        input, select, textarea {
            width: 100%;
            padding: 12px 15px;
            border: 2px solid #e1e1e1;
            border-radius: 8px;
            font-size: 16px;
        }
        input:focus, select:focus, textarea:focus {
            outline: none;
            border-color: #667eea;
        }
        .file-upload {
            border: 2px dashed #667eea;
            border-radius: 8px;
            padding: 30px;
            text-align: center;
            background: #f8f9fa;
            transition: all 0.3s ease;
        }
        .file-upload:hover {
            background: #f0f4ff;
        }
        .file-upload input {
            display: none;
        }
        .file-label {
            display: inline-block;
            padding: 12px 25px;
            background: #667eea;
            color: white;
            border-radius: 8px;
            cursor: pointer;
            font-weight: bold;
            transition: background 0.3s ease;
        }
        .file-label:hover {
            background: #5a6fd8;
        }
        .file-name {
            margin-top: 10px;
            color: #666;
            font-size: 14px;
        }
        .btn {
            display: inline-block;
            padding: 12px 25px;
            background: #667eea;
            color: white;
            text-decoration: none;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-right: 10px;
        }
        .btn:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
        }
        .btn-secondary {
            background: #6c757d;
        }
        .btn-secondary:hover {
            background: #5a6268;
        }
        .error {
            color: #e74c3c;
            text-align: center;
            margin-top: 15px;
            padding: 10px;
            background: #ffeaea;
            border-radius: 5px;
        }
        .action-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 30px;
        }
        .file-format {
            background: #e8f5e8;
            padding: 20px;
            border-radius: 8px;
            margin-top: 20px;
        }
        .file-format h4 {
            margin-bottom: 10px;
            color: #28a745;
        }
        .file-format table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }
        .file-format th, .file-format td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        .file-format th {
            background: #f8f9fa;
        }
        .creation-method {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        .method-tab {
            flex: 1;
            padding: 15px;
            text-align: center;
            background: #f8f9fa;
            border: 2px solid #e1e1e1;
            border-radius: 8px;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.3s ease;
        }
        .method-tab.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        .method-content {
            display: none;
        }
        .method-content.active {
            display: block;
        }
        .question-item {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 15px;
            border-left: 4px solid #667eea;
        }
        .question-header {
            font-weight: bold;
            margin-bottom: 10px;
            color: #333;
        }
        .options-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin: 10px 0;
        }
        .option-item {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .option-label {
            font-weight: bold;
            min-width: 60px;
        }
        .correct-option {
            margin-top: 10px;
        }
        .add-question-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            font-weight: bold;
            margin-top: 10px;
        }
        .add-question-btn:hover {
            background: #218838;
        }
        .remove-question-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 10px;
        }
        .remove-question-btn:hover {
            background: #c82333;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 class="title">📝 创建新考试</h1>
            <p style="color: #666;">请选择创建方式并填写考试信息</p>
        </div>

        <form method="POST" enctype="multipart/form-data" id="examForm">
            <div class="form-group">
                <label for="title">考试标题</label>
                <input type="text" id="title" name="title" placeholder="请输入考试标题" required>
            </div>

            <div class="form-group">
                <label for="exam_type">考试类型</label>
                <select id="exam_type" name="exam_type" required>
                    <option value="">请选择考试类型</option>
                    <option value="随堂测试">随堂测试</option>
                    <option value="单元测验">单元测验</option>
                    <option value="期中考试">期中考试</option>
                    <option value="期末考试">期末考试</option>
                    <option value="模拟考试">模拟考试</option>
                </select>
            </div>

            <div class="creation-method">
                <div class="method-tab active" data-method="file">📁 文件上传</div>
                <div class="method-tab" data-method="manual">✏️ 手动创建</div>
            </div>

            <!-- 文件上传方式 -->
            <div class="method-content active" id="file-method">
                <div class="form-group">
                    <label>上传题目文件</label>
                    <div class="file-upload">
                        <input type="file" id="exam_file" name="exam_file" accept=".xlsx,.xls,.csv">
                        <label for="exam_file" class="file-label">选择文件</label>
                        <div class="file-name" id="file-name">未选择文件</div>
                        <p style="margin-top: 10px; color: #666; font-size: 14px;">
                            支持格式: Excel (.xlsx, .xls) 或 CSV (.csv)
                        </p>
                    </div>
                </div>

                <div class="file-format">
                    <h4>📋 文件格式说明</h4>
                    <p>请确保您的Excel或CSV文件包含以下列：</p>
                    <table>
                        <thead>
                            <tr>
                                <th>列名</th>
                                <th>说明</th>
                                <th>示例</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>题目</td>
                                <td>题目内容</td>
                                <td>下列哪个音符是C大调的主音？</td>
                            </tr>
                            <tr>
                                <td>选项A</td>
                                <td>第一个选项</td>
                                <td>C</td>
                            </tr>
                            <tr>
                                <td>选项B</td>
                                <td>第二个选项</td>
                                <td>D</td>
                            </tr>
                            <tr>
                                <td>选项C</td>
                                <td>第三个选项</td>
                                <td>E</td>
                            </tr>
                            <tr>
                                <td>选项D</td>
                                <td>第四个选项</td>
                                <td>F</td>
                            </tr>
                            <tr>
                                <td>正确答案</td>
                                <td>正确选项字母 (A/B/C/D)</td>
                                <td>A</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            <!-- 手动创建方式 -->
            <div class="method-content" id="manual-method">
                <div class="form-group">
                    <label>题目数量</label>
                    <input type="number" id="question_count" name="question_count" min="1" max="50" value="1" onchange="updateQuestionForms()">
                </div>

                <div id="questions-container">
                    <!-- 题目表单将通过JavaScript动态生成 -->
                </div>

                <button type="button" class="add-question-btn" onclick="addQuestion()">+ 添加题目</button>
            </div>

            {% if error %}
            <div class="error">{{ error }}</div>
            {% endif %}

            <div class="action-buttons">
                <a href="/dashboard" class="btn btn-secondary">返回主页</a>
                <button type="submit" class="btn">创建考试</button>
            </div>
        </form>
    </div>

    <script>
        // 文件选择显示
        document.getElementById('exam_file').addEventListener('change', function(e) {
            const fileName = e.target.files[0] ? e.target.files[0].name : '未选择文件';
            document.getElementById('file-name').textContent = fileName;
        });

        // 切换创建方式
        document.querySelectorAll('.method-tab').forEach(tab => {
            tab.addEventListener('click', function() {
                // 移除所有active类
                document.querySelectorAll('.method-tab').forEach(t => t.classList.remove('active'));
                document.querySelectorAll('.method-content').forEach(c => c.classList.remove('active'));
                
                // 添加active类到当前选项卡
                this.classList.add('active');
                const method = this.getAttribute('data-method');
                document.getElementById(method + '-method').classList.add('active');
            });
        });

        let questionCount = 1;

        function updateQuestionForms() {
            const count = parseInt(document.getElementById('question_count').value);
            const container = document.getElementById('questions-container');
            
            // 确保count在合理范围内
            if (count < 1) count = 1;
            if (count > 50) count = 50;
            
            // 更新题目数量
            questionCount = count;
            
            // 重新生成题目表单
            container.innerHTML = '';
            for (let i = 0; i < count; i++) {
                addQuestionForm(i);
            }
        }

        function addQuestion() {
            const count = parseInt(document.getElementById('question_count').value);
            document.getElementById('question_count').value = count + 1;
            updateQuestionForms();
        }

        function addQuestionForm(index) {
            const container = document.getElementById('questions-container');
            const questionDiv = document.createElement('div');
            questionDiv.className = 'question-item';
            questionDiv.innerHTML = `
                <div class="question-header">题目 ${index + 1}</div>
                <div class="form-group">
                    <label>题目内容</label>
                    <textarea name="question_${index}" placeholder="请输入题目内容..." required></textarea>
                </div>
                <div class="options-grid">
                    <div class="option-item">
                        <span class="option-label">选项A:</span>
                        <input type="text" name="option_a_${index}" placeholder="选项A内容" required>
                    </div>
                    <div class="option-item">
                        <span class="option-label">选项B:</span>
                        <input type="text" name="option_b_${index}" placeholder="选项B内容" required>
                    </div>
                    <div class="option-item">
                        <span class="option-label">选项C:</span>
                        <input type="text" name="option_c_${index}" placeholder="选项C内容" required>
                    </div>
                    <div class="option-item">
                        <span class="option-label">选项D:</span>
                        <input type="text" name="option_d_${index}" placeholder="选项D内容" required>
                    </div>
                </div>
                <div class="form-group correct-option">
                    <label>正确答案</label>
                    <select name="correct_${index}" required>
                        <option value="">请选择正确答案</option>
                        <option value="A">A</option>
                        <option value="B">B</option>
                        <option value="C">C</option>
                        <option value="D">D</option>
                    </select>
                </div>
                ${index > 0 ? `<button type="button" class="remove-question-btn" onclick="removeQuestion(${index})">删除此题</button>` : ''}
            `;
            container.appendChild(questionDiv);
        }

        function removeQuestion(index) {
            const count = parseInt(document.getElementById('question_count').value);
            document.getElementById('question_count').value = count - 1;
            updateQuestionForms();
        }

        // 初始化题目表单
        updateQuestionForms();
    </script>
</body>
</html>'''
    
    with open(os.path.join(templates_dir, 'create_exam.html'), 'w', encoding='utf-8') as f:
        f.write(create_exam_html)

    # 修复的考试页面模板
    exam_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试页面 - 音乐考试系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.1);
        }
        .exam-header {
            text-align: center;
            margin-bottom: 30px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f0f0f0;
        }
        .exam-title {
            color: #333;
            font-size: 28px;
            margin-bottom: 10px;
        }
        .timer {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #667eea;
            color: white;
            padding: 15px 20px;
            border-radius: 10px;
            font-size: 18px;
            font-weight: bold;
            box-shadow: 0 5px 15px rgba(102,126,234,0.3);
        }
        .question {
            margin-bottom: 30px;
            padding: 25px;
            background: #f8f9fa;
            border-radius: 12px;
            border-left: 5px solid #667eea;
            transition: all 0.3s ease;
        }
        .question:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .question-title {
            font-size: 18px;
            color: #333;
            margin-bottom: 20px;
            font-weight: bold;
            line-height: 1.5;
        }
        .options {
            display: grid;
            gap: 12px;
        }
        .option-label {
            display: flex;
            align-items: center;
            padding: 15px;
            background: white;
            border: 2px solid #e1e1e1;
            border-radius: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .option-label:hover {
            border-color: #667eea;
            background: #f0f4ff;
            transform: translateX(5px);
        }
        .option-label.selected {
            border-color: #28a745;
            background: #e8f5e8;
        }
        .option-label input {
            margin-right: 15px;
            transform: scale(1.2);
        }
        .option-text {
            display: flex;
            align-items: center;
            font-size: 16px;
        }
        .option-letter {
            display: inline-block;
            width: 28px;
            height: 28px;
            background: #667eea;
            color: white;
            border-radius: 50%;
            text-align: center;
            line-height: 28px;
            margin-right: 15px;
            font-weight: bold;
        }
        .submit-btn {
            display: block;
            width: 200px;
            margin: 40px auto 0;
            padding: 15px;
            background: #28a745;
            color: white;
            border: none;
            border-radius: 10px;
            font-size: 18px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .submit-btn:hover {
            background: #218838;
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(40,167,69,0.3);
        }
        .progress-bar {
            background: #e9ecef;
            border-radius: 10px;
            height: 8px;
            margin: 20px 0;
            overflow: hidden;
        }
        .progress {
            background: #28a745;
            height: 100%;
            transition: width 0.3s ease;
        }
        .progress-text {
            text-align: center;
            color: #666;
            margin-bottom: 10px;
            font-size: 14px;
        }
        .question-counter {
            text-align: center;
            color: #667eea;
            font-weight: bold;
            margin-bottom: 20px;
            font-size: 16px;
        }
        .nav-btn {
            padding: 12px 25px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 0 10px;
        }
        .nav-btn:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102,126,234,0.3);
        }
        .nav-btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        .nav-btn.prev {
            background: #6c757d;
        }
        .nav-btn.prev:hover:not(:disabled) {
            background: #5a6268;
        }
        .navigation {
            display: flex;
            justify-content: space-between;
            margin-top: 25px;
            align-items: center;
        }
    </style>
</head>
<body>
    <div class="timer" id="timer">剩余时间: 60:00</div>
    
    <div class="container">
        <div class="exam-header">
            <h1 class="exam-title">{{ exam.title }}</h1>
            <p style="color: #666;">请认真作答，祝您考试顺利！</p>
        </div>
        
        <div class="question-counter" id="questionCounter">题目 1 / {{ questions|length }}</div>
        <div class="progress-bar">
            <div class="progress" id="progressBar" style="width: 0%"></div>
        </div>
        <div class="progress-text" id="progressText">已完成 0%</div>
        
        <form method="POST" id="examForm">
            {% for question in questions %}
            <div class="question" id="question-{{ loop.index0 }}" style="display: {% if loop.index0 == 0 %}block{% else %}none{% endif %};">
                <div class="question-title">
                    {{ loop.index }}. {{ question.content }}
                </div>
                <div class="options">
                    {% for option in question.options %}
<label class="option-label" data-question="{{ loop.index0 }}" data-option="{{ loop.index0 }}">
    <input type="radio" 
           name="q{{ loop.index0 }}" 
           value="{{ option }}"
           onchange="selectOption(this)">
    <div class="option-text">
        <span class="option-letter">{{ ['A','B','C','D'][loop.index0] }}</span>
        {{ option }}
    </div>
</label>
{% endfor %}
                </div>
                
                <div class="navigation">
                    <button type="button" class="nav-btn prev" onclick="showQuestion({{ loop.index0 - 1 }})" {% if loop.index0 == 0 %}disabled{% endif %}>
                        ← 上一题
                    </button>
                    
                    {% if loop.index < questions|length %}
                    <button type="button" class="nav-btn next" onclick="showQuestion({{ loop.index0 + 1 }})">
                        下一题 →
                    </button>
                    {% else %}
                    <button type="submit" class="submit-btn">提交试卷</button>
                    {% endif %}
                </div>
            </div>
            {% endfor %}
        </form>
    </div>

    <script>
        let currentQuestion = 0;
        const totalQuestions = {{ questions|length }};
        const answeredQuestions = new Set();
        
        // 更新进度
        function updateProgress() {
            const progress = (answeredQuestions.size / totalQuestions) * 100;
            document.getElementById('progressBar').style.width = progress + '%';
            document.getElementById('progressText').textContent = `已完成 ${Math.round(progress)}%`;
        }
        
        // 显示指定题目
        function showQuestion(index) {
            if (index >= 0 && index < totalQuestions) {
                document.getElementById('question-' + currentQuestion).style.display = 'none';
                document.getElementById('question-' + index).style.display = 'block';
                currentQuestion = index;
                
                document.getElementById('questionCounter').textContent = `题目 ${index + 1} / ${totalQuestions}`;
                updateProgress();
                
                // 更新导航按钮状态
                updateNavigationButtons();
            }
        }
        
        // 更新导航按钮状态
        function updateNavigationButtons() {
            const prevButtons = document.querySelectorAll('.nav-btn.prev');
            prevButtons.forEach(btn => {
                btn.disabled = currentQuestion === 0;
            });
        }
        
        // 选择选项
        function selectOption(radio) {
            const label = radio.parentElement;
            const questionIndex = parseInt(label.getAttribute('data-question'));
            
            // 移除同题目其他选项的选中状态
            const options = document.querySelectorAll(`[data-question="${questionIndex}"]`);
            options.forEach(opt => opt.classList.remove('selected'));
            
            // 添加选中状态
            label.classList.add('selected');
            
            // 记录已回答的题目
            answeredQuestions.add(questionIndex);
            updateProgress();
        }
        
        // 倒计时功能
        let timeLeft = {{ exam_time * 60 }};
        const timer = document.getElementById('timer');
        
        function updateTimer() {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            timer.textContent = `剩余时间: ${minutes}:${seconds.toString().padStart(2, '0')}`;
            
            if (timeLeft <= 0) {
                alert('考试时间到！将自动提交答案。');
                document.getElementById('examForm').submit();
            } else {
                timeLeft--;
                setTimeout(updateTimer, 1000);
            }
        }
        
        // 初始化
        updateTimer();
        updateProgress();
        updateNavigationButtons();
        
        // 键盘导航
        document.addEventListener('keydown', function(e) {
            if (e.key === 'ArrowLeft' && currentQuestion > 0) {
                showQuestion(currentQuestion - 1);
            } else if (e.key === 'ArrowRight' && currentQuestion < totalQuestions - 1) {
                showQuestion(currentQuestion + 1);
            }
        });
    </script>
</body>
</html>'''
    
    with open(os.path.join(templates_dir, 'exam.html'), 'w', encoding='utf-8') as f:
        f.write(exam_html)

    # 修复的考试结果页面模板
    exam_result_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试结果 - 音乐考试系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .result-container {
            background: white;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.1);
            max-width: 800px;
            width: 100%;
        }
        .score-circle {
            width: 150px;
            height: 150px;
            border-radius: 50%;
            background: linear-gradient(135deg, #28a745, #20c997);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 42px;
            font-weight: bold;
            margin: 0 auto 20px;
            border: 5px solid white;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .result-title {
            color: #333;
            font-size: 32px;
            margin-bottom: 10px;
            text-align: center;
        }
        .result-details {
            color: #666;
            margin-bottom: 30px;
            text-align: center;
            font-size: 18px;
        }
        .btn {
            display: inline-block;
            padding: 15px 30px;
            background: #667eea;
            color: white;
            text-decoration: none;
            border-radius: 10px;
            font-weight: bold;
            transition: all 0.3s ease;
            margin: 0 10px;
            font-size: 16px;
        }
        .btn:hover {
            background: #5a6fd8;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102,126,234,0.3);
        }
        .question-review {
            margin-top: 40px;
        }
        .review-item {
            padding: 20px;
            margin-bottom: 20px;
            border-radius: 12px;
            background: #f8f9fa;
            border-left: 5px solid #dc3545;
            transition: all 0.3s ease;
        }
        .review-item.correct {
            border-left-color: #28a745;
            background: #e8f5e8;
        }
        .review-item:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .user-answer { 
            color: #dc3545; 
            font-weight: bold;
            background: #ffeaea;
            padding: 2px 8px;
            border-radius: 4px;
            margin: 0 5px;
        }
        .correct-answer { 
            color: #28a745; 
            font-weight: bold;
            background: #e8f5e8;
            padding: 2px 8px;
            border-radius: 4px;
            margin: 0 5px;
        }
        .question-content { 
            font-weight: bold; 
            margin-bottom: 15px; 
            font-size: 16px;
            color: #333;
        }
        .answer-info { 
            margin: 8px 0; 
            font-size: 15px;
        }
        .btn-container { 
            text-align: center; 
            margin-top: 40px;
        }
        .performance-summary {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 20px;
            margin: 30px 0;
        }
        .performance-item {
            text-align: center;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
        }
        .performance-value {
            font-size: 32px;
            font-weight: bold;
            color: #667eea;
            margin-bottom: 5px;
        }
        .performance-label {
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="result-container">
        <div class="score-circle">{{ score }}分</div>
        <h1 class="result-title">
            {% if score >= 60 %}🎉 考试完成！{% else %}📝 继续努力！{% endif %}
        </h1>
        <div class="result-details">
            <p><strong>{{ exam.title }}</strong></p>
            <p>提交时间: {{ current_time.strftime('%Y-%m-%d %H:%M') }}</p>
        </div>
        
        <div class="performance-summary">
            <div class="performance-item">
                <div class="performance-value">{{ correct_count }}/{{ total_questions }}</div>
                <div class="performance-label">正确题数</div>
            </div>
            <div class="performance-item">
                <div class="performance-value">{{ "%.1f"|format((correct_count / total_questions * 100) if total_questions > 0 else 0) }}%</div>
                <div class="performance-label">正确率</div>
            </div>
            <div class="performance-item">
                <div class="performance-value">{{ score }}分</div>
                <div class="performance-label">最终得分</div>
            </div>
        </div>
        
        <div class="question-review">
            <h3 style="color: #333; margin-bottom: 20px; text-align: center;">📋 题目回顾</h3>
            {% for i in range(total_questions) %}
            {% set question = questions[i] %}
            {% set user_answer = answers.get('q' ~ i|string, '未作答') %}
            {% set correct_answer = question.correct %}
            {% set is_correct = user_answer == correct_answer %}
            <div class="review-item {% if is_correct %}correct{% else %}incorrect{% endif %}">
                <div class="question-content">题目 {{ i + 1 }}: {{ question.content }}</div>
                <div class="answer-info">
                    <span>你的答案: </span>
                    <span class="user-answer">{{ user_answer }}</span>
                    {% if is_correct %}
                    <span style="color: #28a745; margin-left: 10px;">✅ 正确</span>
                    {% else %}
                    <span style="color: #dc3545; margin-left: 10px;">❌ 错误</span>
                    {% endif %}
                </div>
                {% if not is_correct %}
                <div class="answer-info">
                    <span>正确答案: </span>
                    <span class="correct-answer">{{ correct_answer }}</span>
                </div>
                {% endif %}
            </div>
            {% endfor %}
        </div>
        
        <div class="btn-container">
            <a href="/dashboard" class="btn">返回主页</a>
            <a href="/results" class="btn" style="background: #28a745;">查看详细成绩</a>
        </div>
    </div>
</body>
</html>'''
    
    with open(os.path.join(templates_dir, 'exam_result.html'), 'w', encoding='utf-8') as f:
        f.write(exam_result_html)

    # 学生成绩页面模板（保持不变）
    student_results_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的成绩 - 音乐考试系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container { max-width: 1000px; margin: 0 auto; }
        .header {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            text-align: center;
        }
        .title { color: #333; font-size: 28px; margin-bottom: 10px; }
        .btn {
            display: inline-block;
            padding: 12px 25px;
            background: #667eea;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: bold;
            transition: all 0.3s ease;
            margin: 10px;
        }
        .btn:hover { background: #5a6fd8; transform: translateY(-2px); }
        .record-card {
            background: white;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
        }
        .record-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        .record-info h3 { color: #333; margin-bottom: 8px; }
        .record-info p { color: #666; margin: 4px 0; }
        .score {
            font-size: 32px;
            font-weight: bold;
            color: #28a745;
        }
        .no-data {
            text-align: center;
            color: #666;
            padding: 60px 20px;
            background: white;
            border-radius: 15px;
            font-style: italic;
        }
        .delete-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            margin-left: 15px;
            transition: all 0.3s ease;
        }
        .delete-btn:hover {
            background: #c82333;
            transform: translateY(-2px);
        }
        .score-excellent { color: #28a745; }
        .score-good { color: #17a2b8; }
        .score-average { color: #ffc107; }
        .score-poor { color: #dc3545; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 class="title">📊 我的考试成绩</h1>
            <p style="color: #666;">查看您的所有考试记录</p>
            <a href="/dashboard" class="btn">返回主页</a>
        </div>

        {% if records %}
            {% for record in records %}
            <div class="record-card">
                <div class="record-info">
                    <h3>{{ record.exam.title }}</h3>
                    <p>考试类型: {{ record.exam.exam_type or '常规测试' }}</p>
                    <p>提交时间: {{ record.submitted_at.strftime('%Y-%m-%d %H:%M') }}</p>
                </div>
                <div style="display: flex; align-items: center;">
                    <div class="score 
                        {% if record.score >= 90 %}score-excellent
                        {% elif record.score >= 70 %}score-good
                        {% elif record.score >= 60 %}score-average
                        {% else %}score-poor{% endif %}">
                        {{ record.score }}分
                    </div>
                    <button class="delete-btn" onclick="if(confirm('确定要删除这条记录吗？')) window.location.href='/delete_record/{{ record.id }}'">删除</button>
                </div>
            </div>
            {% endfor %}
        {% else %}
            <div class="no-data">
                📝 您还没有参加任何考试，<a href="/dashboard" style="color: #667eea;">去参加考试吧！</a>
            </div>
        {% endif %}
    </div>
</body>
</html>'''
    
    with open(os.path.join(templates_dir, 'student_results.html'), 'w', encoding='utf-8') as f:
        f.write(student_results_html)

    # 教师成绩管理页面模板（保持不变）
    teacher_results_html = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>成绩管理 - 音乐考试系统</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .container { max-width: 1200px; margin: 0 auto; }
        .header {
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
            margin-bottom: 30px;
            text-align: center;
        }
        .title { color: #333; font-size: 28px; margin-bottom: 10px; }
        .btn {
            display: inline-block;
            padding: 12px 25px;
            background: #667eea;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-weight: bold;
            transition: all 0.3s ease;
            margin: 10px;
        }
        .btn:hover { background: #5a6fd8; transform: translateY(-2px); }
        .record-card {
            background: white;
            padding: 25px;
            border-radius: 12px;
            margin-bottom: 20px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        .record-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        .record-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        .student-info { color: #333; font-weight: bold; font-size: 18px; }
        .exam-info { color: #666; margin: 5px 0; }
        .score {
            font-size: 24px;
            font-weight: bold;
            color: #28a745;
        }
        .no-data {
            text-align: center;
            color: #666;
            padding: 60px 20px;
            background: white;
            border-radius: 15px;
            font-style: italic;
        }
        .delete-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            margin-top: 10px;
            transition: all 0.3s ease;
        }
        .delete-btn:hover {
            background: #c82333;
            transform: translateY(-2px);
        }
        .record-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 10px;
        }
        .score-excellent { color: #28a745; }
        .score-good { color: #17a2b8; }
        .score-average { color: #ffc107; }
        .score-poor { color: #dc3545; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 class="title">👨‍🎓 学生成绩管理</h1>
            <p style="color: #666;">查看所有学生的考试记录</p>
            <a href="/dashboard" class="btn">返回主页</a>
        </div>

        {% if records %}
            {% for record in records %}
            <div class="record-card">
                <div class="record-header">
                    <div class="student-info">{{ record.student.username }}</div>
                    <div class="score 
                        {% if record.score >= 90 %}score-excellent
                        {% elif record.score >= 70 %}score-good
                        {% elif record.score >= 60 %}score-average
                        {% else %}score-poor{% endif %}">
                        {{ record.score }}分
                    </div>
                </div>
                <div class="exam-info">
                    <strong>{{ record.exam.title }}</strong> - {{ record.exam.exam_type or '常规测试' }}
                </div>
                <div class="exam-info">
                    提交时间: {{ record.submitted_at.strftime('%Y-%m-%d %H:%M') }}
                </div>
                <div class="record-actions">
                    <div></div>
                    <button class="delete-btn" onclick="if(confirm('确定要删除这条记录吗？')) window.location.href='/delete_record/{{ record.id }}'">删除记录</button>
                </div>
            </div>
            {% endfor %}
        {% else %}
            <div class="no-data">
                📊 暂无学生考试记录
            </div>
        {% endif %}
    </div>
</body>
</html>'''
    
    with open(os.path.join(templates_dir, 'teacher_results.html'), 'w', encoding='utf-8') as f:
        f.write(teacher_results_html)

    print("所有模板文件创建完成！")

if __name__ == '__main__':
    # 创建模板文件（首次运行）
    if not os.path.exists('templates'):
        create_templates()
    
    # 部署配置
    port = int(os.environ.get('PORT', 5000))
    debug = os.environ.get('DEBUG', 'False').lower() == 'true'
    
    app.run(
        host='0.0.0.0', 
        port=port, 
        debug=debug,
        # 生产环境配置
        use_reloader=debug,
        use_debugger=debug
    )